/**
 * 文档列表页面
 * 显示所有已保存的文档，支持新建、打开、删除操作
 */

import React, { useState, useEffect } from 'react'
import { List, Button, Spin, Result, Modal, Typography, Space, Dropdown, Menu, message, Checkbox } from 'antd'
import { PlusOutlined, FileTextOutlined, DownOutlined, SettingOutlined, DeleteOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons'
import { useDocumentList } from '../../hooks/useDocumentList'
import { DocumentListItem } from './DocumentListItem'
import { VirtualizedDocumentList } from './VirtualizedDocumentList'
import { EmptyState } from './EmptyState'
import { TemplatePicker, TemplateManager } from '../../components/Templates'
import { templateService, DocumentTemplate } from '../../../services/templates'
import { useNavigate } from 'react-router-dom'
import {
  SparkStoryboardConfigDialog,
  GenerationProgressDialog,
  SuccessDialog
} from '../../components/SparkStoryboard'
import {
  SparkStoryboardConfig,
  StoryboardGenerationRequest,
  GenerationProgress
} from '../../../types/sparkStoryboard'
import { htmlToMarkdown } from '../../utils/markdown/htmlToMarkdown'
import { ContentType } from '../../../types/document'

const { Title, Paragraph } = Typography

const DocumentListPage: React.FC = () => {
  const navigate = useNavigate()
  const {
    documents,
    isLoading,
    error,
    selectedIds,
    loadDocuments,
    deleteDocument,
    batchDeleteDocuments,
    toggleSelectDocument,
    selectAllDocuments,
    clearSelection,
    createNewDocument,
    openDocument
  } = useDocumentList()

  // 选择模式状态
  const [selectionMode, setSelectionMode] = useState(false)

  // 模板相关状态
  const [templatePickerVisible, setTemplatePickerVisible] = useState(false)
  const [templateManagerVisible, setTemplateManagerVisible] = useState(false)
  const [templateServiceInitialized, setTemplateServiceInitialized] = useState(false)

  // 火花分镜相关状态
  const [sparkStoryboardState, setSparkStoryboardState] = useState<{
    configDialogVisible: boolean
    progressDialogVisible: boolean
    successDialogVisible: boolean
    selectedDocumentId: string | null
    selectedDocumentTitle: string
    selectedDocumentWordCount: number
    generationProgress: GenerationProgress
    generatedProjectId: string | null
    generatedSceneCount: number
    generatedTotalDuration: number
  }>({
    configDialogVisible: false,
    progressDialogVisible: false,
    successDialogVisible: false,
    selectedDocumentId: null,
    selectedDocumentTitle: '',
    selectedDocumentWordCount: 0,
    generationProgress: {
      phase: 'analyzing',
      message: '',
      percentage: 0
    },
    generatedProjectId: null,
    generatedSceneCount: 0,
    generatedTotalDuration: 0
  })

  // 初始化模板服务
  useEffect(() => {
    const initTemplateService = async () => {
      try {
        const result = await templateService.initialize()
        if (result.success) {
          setTemplateServiceInitialized(true)
          console.log('[文档列表] 模板服务初始化成功')
        } else {
          console.error('[文档列表] 模板服务初始化失败:', result.error)
          message.warning('模板服务初始化失败，模板功能可能无法正常使用')
        }
      } catch (error) {
        console.error('[文档列表] 模板服务初始化异常:', error)
      }
    }
    
    initTemplateService()
  }, [])

  // 从模板创建文档
  const handleCreateFromTemplate = async (template: DocumentTemplate) => {
    try {
      console.log('[文档列表] 开始从模板创建文档:', template)
      
      const result = await templateService.createDocumentFromTemplate(template.id)
      console.log('[文档列表] 模板服务返回结果:', result)
      
      if (result.success) {
        console.log('[文档列表] 准备保存文档:', result.data)
        
        // 保存新文档
        const { getStorage } = await import('../../../services/storage')
        console.log('[文档列表] 成功导入存储服务')
        
        const storageAdapter = await getStorage()
        console.log('[文档列表] 获取存储适配器成功:', storageAdapter)
        
        const saveResult = await storageAdapter.saveContent(result.data)
        console.log('[文档列表] 存储保存结果:', saveResult)
        
        if (saveResult.ok) {
          message.success(`已从模板"${template.name}"创建新文档`)
          setTemplatePickerVisible(false)
          
          // 刷新文档列表
          await loadDocuments()
          
          // 导航到编辑器
          navigate(`/text/editor/${result.data.id}`)
        } else {
          console.error('[文档列表] 保存文档失败:', saveResult.error)
          message.error(`保存文档失败: ${saveResult.error?.message || '未知错误'}`)
        }
      } else {
        console.error('[文档列表] 模板服务返回错误:', result.error)
        message.error(`从模板创建文档失败: ${result.error}`)
      }
    } catch (error) {
      console.error('[文档列表] 从模板创建文档异常:', error)
      console.error('[文档列表] 错误堆栈:', error instanceof Error ? error.stack : '无堆栈信息')
      message.error(`从模板创建文档失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  // 创建菜单
  const createMenuItems = [
    {
      key: 'blank',
      icon: <PlusOutlined />,
      label: '空白文档',
      onClick: createNewDocument
    },
    {
      key: 'template',
      icon: <FileTextOutlined />,
      label: '从模板创建',
      onClick: () => setTemplatePickerVisible(true),
      disabled: !templateServiceInitialized
    }
  ]

  const handleDeleteDocument = async (id: string, title: string) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除文档"${title || '无标题文档'}"吗？此操作无法撤销。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        await deleteDocument(id)
      }
    })
  }

  // 开启选择模式
  const handleEnterSelectionMode = () => {
    setSelectionMode(true)
    clearSelection()
  }

  // 退出选择模式
  const handleExitSelectionMode = () => {
    setSelectionMode(false)
    clearSelection()
  }

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedIds.size === 0) {
      message.warning('请先选择要删除的文档')
      return
    }

    Modal.confirm({
      title: '批量删除确认',
      content: `确定要删除选中的 ${selectedIds.size} 个文档吗？此操作无法撤销。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        await batchDeleteDocuments(Array.from(selectedIds))
        setSelectionMode(false)
      }
    })
  }

  // 全选/取消全选
  const handleToggleSelectAll = () => {
    if (selectedIds.size === documents.length) {
      clearSelection()
    } else {
      selectAllDocuments()
    }
  }

  // 火花分镜：打开配置对话框
  const handleOpenSparkStoryboardConfig = async (documentId: string) => {
    try {
      // 获取文档详情
      const { getStorage } = await import('../../../services/storage')
      const storageAdapter = await getStorage()
      const result = await storageAdapter.getContentById(documentId)

      if (!result.ok || !result.data) {
        message.error('无法读取文档内容')
        return
      }

      const document = result.data
      if (document.type !== ContentType.TEXT_DOCUMENT) {
        message.error('只能将文本文档转为分镜')
        return
      }

      const wordCount = document.data.wordCount || 0

      setSparkStoryboardState(prev => ({
        ...prev,
        configDialogVisible: true,
        selectedDocumentId: documentId,
        selectedDocumentTitle: document.title,
        selectedDocumentWordCount: wordCount
      }))
    } catch (error) {
      console.error('[火花分镜] 打开配置对话框失败:', error)
      message.error('打开配置失败')
    }
  }

  // 火花分镜：开始生成
  const handleStartStoryboardGeneration = async (config: SparkStoryboardConfig) => {
    try {
      console.log('[火花分镜] 开始生成:', config)

      // 关闭配置对话框，显示进度对话框
      setSparkStoryboardState(prev => ({
        ...prev,
        configDialogVisible: false,
        progressDialogVisible: true,
        generationProgress: {
          phase: 'analyzing',
          message: '正在读取文档内容...',
          percentage: 0
        }
      }))

      // 获取文档内容 (0-5%)
      const { getStorage } = await import('../../../services/storage')
      const storageAdapter = await getStorage()

      setSparkStoryboardState(prev => ({
        ...prev,
        generationProgress: {
          phase: 'analyzing',
          message: '正在读取文档...',
          percentage: 2
        }
      }))

      const result = await storageAdapter.getContentById(config.articleId)

      if (!result.ok || !result.data || result.data.type !== ContentType.TEXT_DOCUMENT) {
        message.error('无法读取文档内容')
        setSparkStoryboardState(prev => ({
          ...prev,
          progressDialogVisible: false
        }))
        return
      }

      const document = result.data
      const articleContent = document.data.content

      // 转换HTML为纯文本 (5%)
      setSparkStoryboardState(prev => ({
        ...prev,
        generationProgress: {
          phase: 'analyzing',
          message: '正在转换文档格式...',
          percentage: 5
        }
      }))

      const articlePlainText = htmlToMarkdown(articleContent)
        .replace(/[#*`_\[\]]/g, '') // 移除Markdown标记
        .replace(/\n{3,}/g, '\n\n') // 规范化换行
        .trim()

      // 限制文本长度
      const maxLength = 5000
      const limitedText = articlePlainText.length > maxLength
        ? articlePlainText.substring(0, maxLength) + '...'
        : articlePlainText

      console.log('[火花分镜] 文章纯文本长度:', limitedText.length)

      // 检查内容是否为空
      if (!limitedText || limitedText.length < 10) {
        message.error('文档内容为空或太短，无法生成分镜')
        setSparkStoryboardState(prev => ({
          ...prev,
          progressDialogVisible: false
        }))
        return
      }

      // 构建生成请求 (8%)
      setSparkStoryboardState(prev => ({
        ...prev,
        generationProgress: {
          phase: 'analyzing',
          message: '准备生成请求...',
          percentage: 8
        }
      }))

      const request: StoryboardGenerationRequest = {
        config,
        articleContent,
        articlePlainText: limitedText
      }

      // 调用AI服务生成分镜
      const { AIService } = await import('../../../services/ai/aiService')
      const { SparkStoryboardService } = await import('../../../services/ai/sparkStoryboardService')
      const { getAIConfig } = await import('../../../services/ai/config')

      // 获取AI配置
      const aiConfig = getAIConfig()

      if (!aiConfig || !aiConfig.apiKey) {
        message.error('请先在AI设置中配置API密钥')
        setSparkStoryboardState(prev => ({
          ...prev,
          progressDialogVisible: false
        }))
        return
      }

      const aiService = new AIService({
        openaiApiKey: aiConfig.apiKey,
        baseURL: aiConfig.apiBaseUrl,
        model: aiConfig.model  // 传递model参数，硅基流动API强制要求
      })

      const sparkService = new SparkStoryboardService(aiService)

      // 生成分镜 (从10%开始由Service接管)
      const storyboardResult = await sparkService.generateStoryboard(
        request,
        (progress) => {
          setSparkStoryboardState(prev => ({
            ...prev,
            generationProgress: progress
          }))
        }
      )

      if (!storyboardResult.ok || !storyboardResult.data) {
        console.error('[火花分镜] 生成失败:', storyboardResult.error)
        message.error(`生成失败: ${storyboardResult.error || '未知错误'}`)
        setSparkStoryboardState(prev => ({
          ...prev,
          progressDialogVisible: false
        }))
        return
      }

      console.log('[火花分镜] 生成成功:', storyboardResult.data)

      // 保存分镜项目
      const { storyboardProjectService } = await import('../../../services/storage/storyboardProjectService')

      const createResult = await storyboardProjectService.createProject({
        name: `${config.articleTitle} - 分镜`,
        description: `由文本文档"${config.articleTitle}"自动生成的分镜脚本`,
        template: 'custom',
        status: 'draft',
        storyboardData: storyboardResult.data,
        tags: ['AI生成', '火花分镜']
      })

      console.log('[火花分镜] 项目保存成功:', createResult)

      // 显示成功对话框
      setSparkStoryboardState(prev => ({
        ...prev,
        progressDialogVisible: false,
        successDialogVisible: true,
        generatedProjectId: createResult.id,
        generatedSceneCount: storyboardResult.data.scenes.length,
        generatedTotalDuration: storyboardResult.data.totalDuration
      }))

      message.success('分镜生成成功！')
    } catch (error) {
      console.error('[火花分镜] 生成异常:', error)
      message.error(`生成失败: ${error instanceof Error ? error.message : '未知错误'}`)
      setSparkStoryboardState(prev => ({
        ...prev,
        progressDialogVisible: false
      }))
    }
  }

  // 火花分镜：立即编辑
  const handleEditStoryboard = () => {
    if (sparkStoryboardState.generatedProjectId) {
      navigate(`/storyboard/project/${sparkStoryboardState.generatedProjectId}`)
    }
  }

  // 火花分镜：关闭成功对话框
  const handleCloseSuccessDialog = () => {
    setSparkStoryboardState(prev => ({
      ...prev,
      successDialogVisible: false,
      selectedDocumentId: null,
      selectedDocumentTitle: '',
      selectedDocumentWordCount: 0,
      generatedProjectId: null,
      generatedSceneCount: 0,
      generatedTotalDuration: 0
    }))
  }

  if (error) {
    return (
      <div style={{ padding: '24px' }}>
        <Result
          status="error"
          title="加载失败"
          subTitle={error.message}
          extra={
            <Button type="primary" onClick={loadDocuments}>
              重新加载
            </Button>
          }
        />
      </div>
    )
  }

  if (isLoading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" tip="加载文档列表...">
          <div style={{ minHeight: '200px' }} />
        </Spin>
      </div>
    )
  }

  if (documents.length === 0) {
    return (
      <div style={{ padding: '24px' }}>
        <EmptyState 
          onCreateNew={createNewDocument}
          onCreateFromTemplate={() => setTemplatePickerVisible(true)}
          templateEnabled={templateServiceInitialized}
        />
        
        {/* 模板选择器 */}
        <TemplatePicker
          visible={templatePickerVisible}
          onSelect={handleCreateFromTemplate}
          onCancel={() => setTemplatePickerVisible(false)}
        />
      </div>
    )
  }

  return (
    <div style={{ padding: '24px', maxWidth: 1200, margin: '0 auto' }}>
      <div style={{ marginBottom: '24px' }}>
        <Title level={2}>文本稿件创建</Title>
        <Paragraph type="secondary">
          管理你的文档，开始创作
        </Paragraph>
      </div>

      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: '24px'
      }}>
        <Space>
          <span style={{ fontSize: 16, fontWeight: 500 }}>
            我的文档 ({documents.length})
          </span>
          {selectionMode && (
            <span style={{ color: '#1890ff' }}>
              已选择 {selectedIds.size} 个
            </span>
          )}
        </Space>
        <Space>
          {selectionMode ? (
            <>
              <Checkbox
                checked={selectedIds.size === documents.length && documents.length > 0}
                indeterminate={selectedIds.size > 0 && selectedIds.size < documents.length}
                onChange={handleToggleSelectAll}
              >
                全选
              </Checkbox>
              <Button
                danger
                icon={<DeleteOutlined />}
                onClick={handleBatchDelete}
                disabled={selectedIds.size === 0}
              >
                删除选中 ({selectedIds.size})
              </Button>
              <Button
                icon={<CloseOutlined />}
                onClick={handleExitSelectionMode}
              >
                取消
              </Button>
            </>
          ) : (
            <>
              <Button
                icon={<CheckOutlined />}
                onClick={handleEnterSelectionMode}
              >
                批量管理
              </Button>
              <Button
                icon={<SettingOutlined />}
                onClick={() => setTemplateManagerVisible(true)}
                disabled={!templateServiceInitialized}
              >
                模板管理
              </Button>
              <Dropdown menu={{ items: createMenuItems }} trigger={['click']}>
                <Button type="primary">
                  <PlusOutlined />
                  创建文档
                  <DownOutlined />
                </Button>
              </Dropdown>
            </>
          )}
        </Space>
      </div>

      <VirtualizedDocumentList
        documents={documents}
        onOpen={openDocument}
        onDelete={handleDeleteDocument}
        onConvertToStoryboard={handleOpenSparkStoryboardConfig}
        containerHeight={window.innerHeight - 300} // 根据窗口高度动态计算
        loading={isLoading}
        selectionMode={selectionMode}
        selectedIds={selectedIds}
        onToggleSelect={toggleSelectDocument}
      />

      {/* 模板选择器 */}
      <TemplatePicker
        visible={templatePickerVisible}
        onSelect={handleCreateFromTemplate}
        onCancel={() => setTemplatePickerVisible(false)}
      />

      {/* 模板管理器 */}
      <TemplateManager
        visible={templateManagerVisible}
        onClose={() => setTemplateManagerVisible(false)}
        onTemplateSelect={handleCreateFromTemplate}
      />

      {/* 火花分镜配置对话框 */}
      {sparkStoryboardState.selectedDocumentId && (
        <SparkStoryboardConfigDialog
          visible={sparkStoryboardState.configDialogVisible}
          articleId={sparkStoryboardState.selectedDocumentId}
          articleTitle={sparkStoryboardState.selectedDocumentTitle}
          wordCount={sparkStoryboardState.selectedDocumentWordCount}
          onSubmit={handleStartStoryboardGeneration}
          onCancel={() => setSparkStoryboardState(prev => ({ ...prev, configDialogVisible: false }))}
        />
      )}

      {/* 火花分镜生成进度对话框 */}
      <GenerationProgressDialog
        visible={sparkStoryboardState.progressDialogVisible}
        progress={sparkStoryboardState.generationProgress}
      />

      {/* 火花分镜成功对话框 */}
      <SuccessDialog
        visible={sparkStoryboardState.successDialogVisible}
        projectId={sparkStoryboardState.generatedProjectId || ''}
        sceneCount={sparkStoryboardState.generatedSceneCount}
        totalDuration={sparkStoryboardState.generatedTotalDuration}
        onEdit={handleEditStoryboard}
        onClose={handleCloseSuccessDialog}
      />
    </div>
  )
}

export default DocumentListPage
